/*
   Copyright 2009 Abdulla Abdurakhmanov (abdulla@latestbit.com)
   Original sources are available at www.latestbit.com

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/

package org.latestbit.smartobjects.encrypters;

import java.nio.ByteBuffer;
import java.security.GeneralSecurityException;
import java.util.concurrent.locks.Lock;

import javax.crypto.Cipher;

import org.latestbit.smartobjects.io.ResizableByteBuffer;

public abstract class StdAbstractDataEncrypter implements IDataEncrypter {

	protected Cipher encCipher, decCipher;
	protected Lock encLock = new java.util.concurrent.locks.ReentrantLock();
	protected Lock decLock = new java.util.concurrent.locks.ReentrantLock();
	protected String algorithm;
	protected String algorithmWithoutOptions;
	
	protected StdAbstractDataEncrypter(String algorithm) {
		this.algorithm = algorithm;
		this.algorithmWithoutOptions = algorithm;
		if(this.algorithmWithoutOptions.contains("/")) {
			this.algorithmWithoutOptions = this.algorithmWithoutOptions.split("/")[0];
		}
	}
	
	@Override
	public String getAlgorithm() {
		return algorithm;
	}
	
	public String getAlgorithmWithoutOptions() {
		return algorithmWithoutOptions;
	}	
	
	@Override
	public synchronized void encrypt(ByteBuffer inputData, ResizableByteBuffer output) throws GeneralSecurityException {
		encLock.lock();
		try {
			int inputSize = inputData.limit() - inputData.position();			
			output.prepareToSize( encCipher.getOutputSize( inputSize  ) );
			
			encCipher.doFinal( inputData, output.getBuffer() );
		}
		finally {
			encLock.unlock();
		}
	}

	@Override
	public void decrypt(ByteBuffer encryptedData, ResizableByteBuffer output) throws GeneralSecurityException  {
		decLock.lock();
		try {
			int encryptedDataSize = encryptedData.limit() - encryptedData.position();
			
			output.prepareToSize( decCipher.getOutputSize( encryptedDataSize ) );	
			
			decCipher.doFinal( encryptedData, output.getBuffer() );
			
		}
		finally {
			decLock.unlock();
		}
	}
}
